import os

from enetity_extraction.json_result import generate_return_json


# # 函数：在函数内部定义一个全局集合
# def define_global_set():
#     global court_codes  # 声明全局变量
#     court_codes = set()  # 初始化全局集合
#
#     with open('data/all_court_code.txt', 'r', encoding='utf-8') as f:
#         lines = f.readlines()
#         for line in lines:
#             line = line.strip()
#             court_codes.add(line)


def define_global_set():
    global court_codes  # 声明全局变量
    court_codes = set()  # 初始化全局集合

    # 获取当前工作目录的上级目录
    current_dir = os.getcwd()
    parent_dir = os.path.dirname(current_dir)

    # 定义可能的目录列表
    possible_dirs = [
        current_dir,  # 当前工作目录
        parent_dir  # 上级目录
    ]

    file_found = False
    file_path = ''

    # 遍历目录列表，查找文件
    for directory in possible_dirs:
        potential_path = os.path.join(directory, 'logic_rule', 'data', 'all_court_code.txt')
        if os.path.isfile(potential_path):
            file_path = potential_path
            file_found = True
            break

    if not file_found:
        raise FileNotFoundError("文件'all_court_code.txt'无法在指定文件目录下找到。")

    # 读取文件并填充集合
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip()
                court_codes.add(line)
    except Exception as e:
        raise RuntimeError(f"Error reading the file '{file_path}': {e}")

# 调用函数前，打印当前工作目录
# print(f"Current working directory: {os.getcwd()}")


def create_global_set():
    court_codes = set()  # 初始化全局集合

    # 获取当前工作目录的上级目录
    current_dir = os.getcwd()
    parent_dir = os.path.dirname(current_dir)

    # 定义可能的目录列表
    possible_dirs = [
        current_dir,  # 当前工作目录
        parent_dir  # 上级目录
    ]

    file_found = False
    file_path = ''

    # 遍历目录列表，查找文件
    for directory in possible_dirs:
        potential_path = os.path.join(directory, 'logic_rule', 'data', 'all_court_code.txt')
        if os.path.isfile(potential_path):
            file_path = potential_path
            file_found = True
            break

    if not file_found:
        raise FileNotFoundError("文件'all_court_code.txt'无法在指定文件目录下找到。")

    # 读取文件并填充集合
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip()
                court_codes.add(line)
    except Exception as e:
        raise RuntimeError(f"Error reading the file '{file_path}': {e}")

    # 调用函数前，打印当前工作目录
    # print(f"Current working directory: {os.getcwd()}")
    return court_codes


def is_valid_court_code(court_codes, date_dic):
    result = generate_return_json()

    if date_dic['法院代字'] == {}:
        # print('法院代字不合法')
        result['type'] = '法院代字缺失'
        # return result
        return None

    text = date_dic['法院代字']['match']
    # result赋值
    result['paragraph_index'] = date_dic['法院代字']['paragraph_index']
    result['start'] = date_dic['法院代字']['start_pos']
    result['end'] = date_dic['法院代字']['end_pos']
    result['offset'] = date_dic['法院代字']['end_pos'] - date_dic['法院代字']['start_pos'] + 1

    if text not in court_codes:
        # print('法院代字不合法')
        result['type'] = '法院代字错误'
        return result

    # print('法院代字合法')
    result['type'] = '法院代字合法'
    # return result
    # return None

# if __name__ == "__main__":
#     define_global_set()
#
#     test_text1 = "京1"  # 不合法
#     is_valid_court_code(test_text1)
#
#     test_text2 = "京7107"  # 不合法
#     is_valid_court_code(test_text2)
#
#     test_text2 = "京0228"  # 合法
#     is_valid_court_code(test_text2)
